/*
 *  Copyright (c) M2TK Project. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package m2tk.assistant.app.ui.component;

import com.formdev.flatlaf.FlatClientProperties;
import com.formdev.flatlaf.extras.FlatSVGIcon;
import net.miginfocom.swing.MigLayout;
import org.kordamp.ikonli.fluentui.FluentUiRegularAL;
import org.kordamp.ikonli.swing.FontIcon;

import javax.swing.*;
import java.awt.*;

import static m2tk.assistant.common.ui.UIConstants.ICON_SIZE_L;
import static m2tk.assistant.common.ui.UIConstants.LIGHT_BLUE;

public class SourceIndicatorButton extends JButton
{
    private int rainbowCounter;
    private Timer timer;

    public SourceIndicatorButton()
    {
        super("输入源", FontIcon.of(FluentUiRegularAL.DEVELOPER_BOARD_24, ICON_SIZE_L, LIGHT_BLUE));
        initUI();
    }

    private void initUI()
    {
        setLayout(new MigLayout("insets 0, align trailing", "", "[center]"));
        setHorizontalAlignment(JButton.LEADING);

        FlatSVGIcon dot = new FlatSVGIcon("images/dot.svg", 28, 28);
        dot.setColorFilter(new FlatSVGIcon.ColorFilter(color -> {
            if (timer.isRunning())
            {
                rainbowCounter += 32;
                rainbowCounter %= 255;
                return Color.getHSBColor(rainbowCounter / 255f, 1, 1);
            }
            return Color.getHSBColor(0, 1, 1);
        }));
        JLabel statusIndicator = new JLabel(dot);

        timer = new Timer(500, e -> statusIndicator.repaint());
        add(statusIndicator, "gapx 75");
        putClientProperty(FlatClientProperties.STYLE,
                          """
                          borderWidth: 0; focusWidth: 0; innerFocusWidth: 0; innerOutlineWidth: 0;
                          background: $Panel.background; hoverBackground: $Button.toolbar.hoverBackground;
                          """);
    }

    public void updateSourceState(boolean active)
    {
        if (active)
        {
            rainbowCounter = 0;
            timer.start();
        } else
        {
            timer.stop();
            repaint(); // 让状态图标颜色复位
        }
    }
}
